import { createRouter, createWebHashHistory } from 'vue-router';
import Login from '@/components/Login';

const routes = [
  // 重定向
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/home/Home.vue'),
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: () => import('../components/Welcome.vue'),
      },
      {
        path: '/users',
        component: () => import('../components/user/Users.vue'),
      },
      {
        path: '/rights',
        component: () => import('../components/power/Rights.vue'),
      },
      {
        path: '/roles',
        component: () => import('../components/power/Roles.vue'),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next();
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token');
  if (!tokenStr) return next('/login');
  next();
});

export default router;
